$(function() {
    $.ajaxPrefilter(function(option) {
        option.url = 'http://ajax.frontend.itheima.net' + option.url
        if (option.url.indexOf('/my') !== -1) {
            option.headers = {
                Authorization: localStorage.getItem('token') || ''
            }
            option.complete = function(res) {
                if (res.responseJSON.status == 1 && res.responseJSON.message === '身份认证失败！') {
                    localStorage.setItem('token', '')
                    location.href = './login.html'
                }
            }
        }
    })
    getUserInfo()


    var layer = layui.layer
    $('#out').on('click', function() {
        layer.confirm('确定退出登录', { icon: 3, title: '提示' }, function(index) {
            localStorage.setItem('token', '')
            location.href = './login.html'

            layer.close(index);
        });
    })
    $('#push').click(function() {
        localStorage.removeItem('num')
    })
})


function getUserInfo() {
    $.ajax({
        method: 'GET',
        url: '/my/userinfo',
        success: function(res) {
            if (res.status !== 0) { return layui.layer.msg('获取失败') }
            renderavatar(res.data)
        },




    })
}

function renderavatar(user) {
    var name = user.nickname || user.username

    $('.welcome').html('欢迎' + name)
    if (user.user_pic !== null) {
        $('.layui-nav-img').attr('src', user.user_pic).show()
        $('.avatar').hide()
    } else {
        $('.layui-nav-img').hide()
        var first = name[0].toUpperCase()
        $('.avatar').html(first).show()
    }
}